package userService

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	userDto "news_for_deepseek_interface/dto/admin/system/user"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
	adminService "news_for_deepseek_interface/service/admin"
	"news_for_deepseek_interface/utils"
	"time"
)

func Create(params userDto.CreateRequest) error {
	db := model.GetInstance().GetDB()

	// 检查用户名是否存在
	var count int64
	if err := db.Model(&adminModel.AdminStruct{}).
		Where("mobile = ?", params.Mobile).
		Count(&count).Error; err != nil {
		return err
	}

	if count > 0 {
		return errors.New("当前手机号已存在")
	}

	var count2 int64
	if err := db.Model(&adminModel.AdminStruct{}).
		Where("username = ?", params.Username).
		Count(&count2).Error; err != nil {
		return err
	}

	if count2 > 0 {
		return errors.New("当前用户名已存在")
	}

	// 生成密码盐
	salt := utils.GenerateString(4)
	if salt == "" {
		return errors.New("随机数生成失败")
	}

	// 生成加密密码
	data := []byte(params.Password + "|" + salt)
	hash := md5.Sum(data)
	hashString := hex.EncodeToString(hash[:])

	expires, _ := time.ParseInLocation("2006-01-02 15:04:05", params.Expires, time.Local)
	city := ""
	province := ""
	area := ""
	if len(params.Region) > 0 {
		province = params.Region[0]
	}

	if len(params.Region) > 1 {
		city = params.Region[1]
	}

	if len(params.Region) > 2 {
		area = params.Region[2]
	}

	// 创建用户
	user := adminModel.AdminStruct{
		Username: params.Username,
		Password: hashString,
		Salt:     salt,
		Status:   params.Status,
		Mobile:   params.Mobile,
		Province: province,
		City:     city,
		Area:     area,
		Address:  params.Address,
		Expires:  expires,
	}
	if err := db.Create(&user).Error; err != nil {
		return fmt.Errorf("创建用户失败: %v", err)
	}

	_, _, _, err := adminService.CreateAccessToken(user.Id)
	if err != nil {
		return fmt.Errorf("创建token失败: %v", err)
	}

	return nil
}
